﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using workflowbackend.CommonResults;

namespace workflowbackend.ExceptionResults
{
    public class ExceptionResultFilter : IExceptionFilter
    {
        public async void OnException(ExceptionContext context)
        {
            // 1、获取异常
            Exception exception = context.Exception;

            ////2. 结果值类型判断
            //if (exception is ExceptionResult exceptionResult)
            //{
            //    // 2.2、结果返回
            //    context.Result = new JsonResult(exception);
            //}
            //else
            //{
            //    // 2.3 结果包装 返回
            //    CommonResult commonResult = new CommonResult();
            //    commonResult.ErrorNo = 404;
            //    commonResult.ErrorInfo = exception.Message;
            //    commonResult.Result = exception.StackTrace;

            //    // 2.4 返回
            //    context.Result = new JsonResult(commonResult);
            //}

            //2. 结果值类型判断
            if (exception is ExceptionResult exceptionResult)
            {
                ExceptionCommonResult exceptionCommonResult = new ExceptionCommonResult();
                exceptionCommonResult.ErrorNo = exceptionResult.ErrorNo;
                exceptionCommonResult.ErrorInfo = exceptionResult.ErrorInfo;
                exceptionCommonResult.Result = exceptionResult.Result;
                // 2.2、结果返回
                context.Result = new JsonResult(exceptionCommonResult);
            }
            else
            {
                // 2.3 结果包装 返回
                CommonResult commonResult = new CommonResult();
                commonResult.ErrorNo = 404;
                commonResult.ErrorInfo = exception.Message;
                commonResult.Result = exception.StackTrace;


                ExceptionCommonResult exceptionCommonResult = new ExceptionCommonResult();
                exceptionCommonResult.ErrorNo = 404;
                exceptionCommonResult.ErrorInfo = exception.Message;
                exceptionCommonResult.Result = exception.StackTrace;
                // 2.4 返回
                context.Result = new JsonResult(exceptionCommonResult);
            }
        }
    }
}
